#include "threadpool.h"

void func_puts_filename(task_t *ptask)
{
     char *otherbuf;
     char *fileargc=strtok_r(ptask->data," ",&otherbuf);
     char filename[100]={0};
     strncpy(filename,fileargc,strlen(fileargc));
     printf("filename: %s\n",filename);
     printf("ptask->peerfd%d\n",ptask->peerfd);
     func_puts_file(ptask->peerfd,filename);
}
//循环读取
int recvCircle(int fd,char *buff,int length)
{
    printf("in recvCircle length:%d\n",length);
    char *pbuf=buff;
    int left=length;
    int ret=0;
    while (left>0)
    {
        ret=recv(fd,pbuf,length,0);
        printf("recvCircle ret:%d\n",ret);
        if(ret==-1&&errno==EINTR)
        {
            continue;
        }
        else if(ret==0)
        {
            close(fd);
            break;
        }else if(ret==-1)
        {
            perror("recv");
            break;
        }
        else
        {
            pbuf+=ret;
            left-=ret;
        }
    }
    return 0;
}


int func_puts_file(int peerfd,char *filename)
{
    //先接受文件长度，如果为-1则为客户端上传错误文件
    size_t filelen=0;
    recvCircle(peerfd,(char *)&filelen,8);
    printf("file length:%ld\n",filelen);
    if(filelen==0)
    {
        printf("client transferfile not susscess\n");
        return -1;
    }
    //1.命令参数包含文件名
    //2.再服务器创建文件
    
    int fd=open(filename,O_RDWR|O_CREAT,0666);
    printf("file fd:%d\n",fd);
    //3.接收文件内容

    //扩容创建文件大小，不能少
    ftruncate(fd,filelen);
    //接受文件内容
    char *p=(char*)mmap(NULL,filelen,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    recvCircle(peerfd,p,filelen);
    munmap(p,filelen);
    close(fd);
    return 0;
}

